package mi.payment.utils.transaction;

import android.content.Context;

import java.util.HashMap;
import java.util.Map;

import mi.payment.bean.db.TradeData;
import mi.payment.bean.temp.Transaction;
import mi.payment.constants.TransactionBitmap;
import mi.payment.db.dao.PaySettlement;
import mi.payment.utils.datacollection.PayDetailCollection;
import mi.payment.utils.iso8583.EncodePackage;
import mi.payment.utils.iso8583.FieldUtils;
import mi.payment.utils.iso8583.MsgField;
import mi.payment.utils.iso8583.Utils;
import mi.payment.utils.secure.TerminalSecure;

/**
 * 签到
 */
public class SignTask extends TransactionTask<TradeData, Void, String> {

    protected SignTask(Context context) {
        super(context, false);
    }

    @Override
    protected void onBegin(TradeData[] params) {
        setReceiveMsgCheck(new SignMsgChecker());
        tradeData = params[0];
        dbBean = tradeData.getPayDetail();
    }

    @Override
    protected String appointResult() {
        return resultStr;
    }

    @Override
    protected Map<String, MsgField> preAssembly() {
        return EncodePackage.preAssemblyBase(TransactionBitmap.BITMAP_SIGN);
    }

    @Override
    protected byte[] changeAndAssembly(Map<String, MsgField> fieldMap) {
        dbBean.TerminalDate = System.currentTimeMillis() / 1000;
        dbBean.tradeAnswerCode = "96";
        dbBean.transType = "00";

        // 更新预组装的Map
        Map<String, MsgField> map = FieldUtils.fillEachFieldValue(fieldMap, tradeData);

        String batchNum = mSystemParamsOperation.getSystemParamsSettings().getBatchNumStart();
        MsgField f060 = map.get("F060");
        String str60 = dbBean.getTransType() + batchNum + "001";
        f060.setDataStr(str60);
        f060.setDataLength(str60.length());

        MsgField F063 = map.get("F063");
        F063.setDataStr(dbBean.getOperatorNo());
        F063.setDataLength(dbBean.getOperatorNo().length());

        // 组包，得到组包后的报文
        return EncodePackage.assembly(map, "0800", TerminalSecure.PROCESSREQUEST_NONE);
    }

    @Override
    protected void onUnpacked(HashMap<String, MsgField> resp) {
        MsgField msgField = resp.get("F039");
        String ret = msgField.getDataStr();
        if (ret.equals("00")) {
            int r = TerminalSecure.SaveWorkingKeys(resp.get("F062").getDataBytes(), true, true); // 保存工作密钥
            if (r != 0) {
                ret = "SF:" + r;
            } else {
                // 获取并保存批次号
                MsgField f060 = resp.get("F060");
                if (f060 != null) {
                    String batchNo = f060.getDataStr().substring(2, 8);
                    if (Utils.isNumeric(batchNo)) {
                        mSystemParamsOperation.saveBatchNumber(batchNo);
                        // 操作数据库
                        Transaction.time = resp.get("F012").getDataStr();
                        Transaction.date = resp.get("F013").getDataStr();
                        settlementTableOperation(dbBean.getOperatorNo(), resp.get("F013").getDataStr(), resp.get("F012").getDataStr());
                    } else {
                        ret = "SF: batchNo error";
                    }
                } else {
                    ret = "SF: batchNo error";
                }
            }
        }
        resultStr = ret;
        PayDetailCollection.getInstance().setSign(true);
        PayDetailCollection.getInstance().uploadData(dbBean);//上送数据给dataService
    }


    /**
     * 操作交易汇总表
     * 当签到成功后判断表中有无记录，无记录则使用签到返回的批次号插入一条记录；有记录则更新日期和操作员号
     */
    private void settlementTableOperation(String operator, String localDate, String localTime) {
        int rowCount = mSettleModel.getRowCount();
        mSystemParamsSettings = mSystemParamsOperation.getSystemParamsSettings();
        String batchNumber = mSystemParamsSettings.getBatchNumStart();
        PaySettlement ps = mSettleModel.getPaySettlementByBatchNo(batchNumber);

        if (rowCount > 0 && ps != null) {
            ps.Operator = operator;
            ps.LocalDate = localDate;
            ps.LocalTime = localTime;
            mSettleModel.update(ps);
        } else {
            mSettleModel.insertByBatchNo(batchNumber);
        }
    }


}
